package com.icongyou.enterprise.talent_pool.service.impl;

import com.icongyou.enterprise.common.result.PageResult;
import com.icongyou.enterprise.data_aggregation.entity.UserEntity;
import com.icongyou.enterprise.data_aggregation.service.DataAggregationService;
import com.icongyou.enterprise.talent_pool.entity.vo.CoreSubmissionVO;
import com.icongyou.enterprise.talent_pool.entity.vo.StudentTalentVO;
import com.icongyou.enterprise.talent_pool.service.StudentTalentService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class StudentTalentServiceImpl implements StudentTalentService {

    private final DataAggregationService dataAggregationService;

    @Override
    public PageResult<StudentTalentVO> getStudentTalents(Integer page, Integer size,
                                                         Boolean teacherRecommended,
                                                         Boolean coreTaskTop30,
                                                         Boolean hasHighPotential) {  // 新增参数

        // 参数校验和默认值设置
        if (page == null || page < 1) page = 1;
        if (size == null || size < 1) size = 10;

        // 计算偏移量
        int offset = (page - 1) * size;

        // 查询分页数据
        List<UserEntity> studentEntities = dataAggregationService.getStudentsWithPagination(offset, size);

        // 转换为VO并进行条件过滤
        List<StudentTalentVO> studentTalents = studentEntities.stream()
                .map(this::convertToStudentTalentVO)
                .filter(vo -> filterByConditions(vo, teacherRecommended, coreTaskTop30, hasHighPotential))  // 传入新参数
                .collect(Collectors.toList());

        // 重新计算实际返回的数量
        long actualTotal = studentTalents.size();
        if (teacherRecommended != null || coreTaskTop30 != null || hasHighPotential != null) {
            // 如果有过滤条件，需要重新计算总数
            actualTotal = studentTalents.size();
        }

        return new PageResult<>(actualTotal, studentTalents, page, size);
    }

    /**
     * 根据条件过滤学生
     */
    // 修改 filterByConditions 方法
    private boolean filterByConditions(StudentTalentVO studentTalent,
                                       Boolean teacherRecommended,
                                       Boolean coreTaskTop30,
                                       Boolean hasHighPotential) {  // 新增参数

        // 如果没有任何过滤条件，直接返回true
        if (teacherRecommended == null && coreTaskTop30 == null && hasHighPotential == null) {
            return true;
        }

        boolean passTeacherRecommended = true;
        boolean passCoreTaskTop30 = true;
        boolean passHighPotential = true;  // 新增

        // 检查教师推荐条件
        if (teacherRecommended != null && teacherRecommended) {
            Boolean isRecommended = dataAggregationService.isTeacherRecommended(studentTalent.getStudentId());
            passTeacherRecommended = isRecommended != null && isRecommended;
        }

        // 检查核心任务top 30%条件
        if (coreTaskTop30 != null && coreTaskTop30) {
            Boolean isTop30 = dataAggregationService.isCoreTaskTop30(studentTalent.getStudentId());
            passCoreTaskTop30 = isTop30 != null && isTop30;
        }

        // 新增：检查高潜力成果条件
        if (hasHighPotential != null && hasHighPotential) {
            Boolean hasHighPotentialResult = dataAggregationService.hasHighPotentialSubmission(studentTalent.getStudentId());
            passHighPotential = hasHighPotentialResult != null && hasHighPotentialResult;
        }

        return passTeacherRecommended && passCoreTaskTop30 && passHighPotential;
    }

    /**
     * 将UserEntity转换为StudentTalentVO
     */
    private StudentTalentVO convertToStudentTalentVO(UserEntity userEntity) {
        StudentTalentVO vo = new StudentTalentVO();
        vo.setStudentId(userEntity.getId());
        vo.setRealName(userEntity.getRealName());
        vo.setAvatar(userEntity.getAvatar());
        vo.setMajor(userEntity.getMajor());
        vo.setRanking(userEntity.getRanking());

        // 获取学校名称（通过租户ID）
        String school = dataAggregationService.getTenantNameByUserId(userEntity.getId());
        vo.setSchool(school);

        // 获取同专业总人数
        Integer totalMajorStudents = dataAggregationService.countStudentsByMajor(
                userEntity.getTenantId(), userEntity.getMajor());
        vo.setTotalMajorStudents(totalMajorStudents != null ? totalMajorStudents : 0);

        // 获取核心成果
        CoreSubmissionVO coreSubmission = dataAggregationService.getCoreSubmission(userEntity.getId());
        vo.setCoreSubmission(coreSubmission);

        // 匹配分数暂时设为null，后续用于搜索排序
        vo.setMatchScore(null);

        return vo;
    }
}